'''
Created on 29/09/2011

@author: Jules <juliocesar.matabielmas@gmail.com>
@author: Ike-kun <ragnell22@gmail.com>
'''

from xml.dom.minidom import getDOMImplementation

class Appender(object):
    def __init__(self,level):
        self.level = level

    def doAppend(self,lines,level):
        if(level > self.getLevel()):
            self.concreteAppend(lines)

    def getLevel(self):
        return self.level

    def setLevel(self,level):
        self.level = level

    def concreteAppend(self,lines):
        pass


class CsvAppender(Appender):
    def __init__(self,ruta,level):
        Appender.__init__(self,level)
        self.ruta = ruta

    def openFile(self):
        try:
            l = open(self.ruta,"w")
            l.close()
            self.l = open(self.ruta,"ab")
            return True
        except IOError:
            return False

    def concreteAppend(self,lines):
        coma = ""
        try:
            for line in lines:
                self.l.write(coma + line)
                coma = ","
            self.l.write("\n")
            return True
        except IOError:
            return False

    def closeFile(self):
        try:
            self.l.flush()
            self.l.close()
            return True
        except IOError:
            return False
        
class XmlAppender(Appender):
    def __init__(self,ruta,level):
        Appender.__init__(self,level)
        self.ruta = ruta
        self.xml = getDOMImplementation().createDocument(None,"log",None)
        self.top = self.xml.documentElement
        self.tags = ["time","priority","category","NDC","message"]

    def openFile(self):
        try:
            self.l = open(self.ruta,"w")
            self.l.write('<?xml version="1.0"?>')
            return True
        except IOError:
            return False

    def concreteAppend(self,lines):
        item = self.xml.createElement("item")
        for i in range(len(self.tags)):
            tag = self.xml.createElement(self.tags[i])
            tag.appendChild(self.xml.createTextNode(lines[i]))
            item.appendChild(tag)
        self.top.appendChild(item)

    def closeFile(self):
        try:
            self.xml.childNodes[0].writexml(self.l,"","\t","\n")
            self.l.flush()
            self.l.close()
            return True
        except IOError:
            return False
